<template>
  <div id="addAndUpdateTable">
    <div class="div">
      <el-form ref="userForm" :model="userForm" label-width="100px" class="selectForm" :rules="rules">

        <el-row :gutter="24">
          <el-col :span="12">

            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="用户名" :disabled="userInfo !== undefined"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" placeholder="姓名"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="手机" prop="telNumber">
              <el-input v-model="userForm.telNumber" placeholder="手机号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮件" prop="email">
              <el-input v-model="userForm.email" placeholder="邮箱"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="头像" >
              <div class="imgPr">
                <el-image 
                  class="img"
                  :src="userForm.headImg" 
                  :preview-src-list="previewImgList">
                </el-image>
                <div class="imgPa">
                  <el-upload
                    ref="upload"
                    :show-file-list="false"
                    :before-upload="beforUpload"
                    :http-request="uploadImageMethod"
                    :file-list="fileList"
                    list-type="picture"
                    action="#"
                    accept=".jpg,.png,.jpeg">
                    <el-button class="changeImg" style="padding: 0px;">
                      <i class="iconfont icon-tianjia"></i>
                    </el-button>
                  </el-upload>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="enabled" label-width="50px">
              <el-select v-model="enable" placeholder="请选择" class="my-el-select" @change="changeEnable" style="width:100%">
                <el-option
                  v-for="item in enables"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="锁定" prop="accountNonLocked" label-width="50px">
              <el-select v-model="accountNonLock" placeholder="请选择" class="my-el-select" @change="changeAccountNonLock" style="width:100%">
                <el-option
                  v-for="item in accountNonLocks"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" prop="sex" label-width="50px">
              <el-select v-model="sex" placeholder="请选择" class="my-el-select" @change="changeSex" style="width:100%">
                <el-option
                  v-for="item in sexs"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        

        <el-form-item label="自我介绍" style="margin-top: 4vh" prop="introduce">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 4}"
            placeholder="自我介绍"
            v-model="userForm.introduce"
            maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
        

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="注册时间">
              <el-input v-model="userForm.createTime" :disabled="true" placeholder="注册时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后登录时间">
              <el-input v-model="userForm.lastLoginTime" :disabled="true" placeholder="最后登录时间"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="角色" class="my-el-select" prop="roles">
              <el-select v-model="role" multiple  placeholder="请选择角色" @change="changeRole" style="width:100%">
                <el-option
                  v-for="item in roles"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <template v-if="isUpdate === true">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="userForm.newPassword"  placeholder="新密码" show-password/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="userForm.confirmPassword"  placeholder="确认密码" show-password/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="当前登录密码" prop="myPassword">
                <el-input v-model="userForm.myPassword" placeholder="当前登录密码" show-password/>
              </el-form-item>
            </el-col>
          </el-row>
        </template>


        <el-row :gutter="24">
          <el-col :span="24" style="text-align:right">
            <el-form-item> 
              <el-button type="primary" @click="onSubmit('userForm')">提交</el-button>
              <el-button type="warning" @click="onReset('userForm')">重置</el-button>
              <el-button @click="onReturn">返回</el-button>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </div>


  </div>
</template>

<script>

import {
  getAllRole,uploadImage,checkUsername
} from '@/assets/request/api.js';

export default {
  name: 'addAndUpdateTable',
  props: ['userInfo'],
  data() {
    var validateUsername = (rule, value, callback) => {
      if(value === '') {
        callback(new Error("请输入用户名"))
      }
      let id = ""
      if(this.operation !== 'insert') {
        id = this.userForm.userId
      }
      checkUsername(value,id).then(res => {
        callback()
      }).catch(err => {
        callback(new Error(err.message))
      })
    };
    return {
      operation: 'insert',
      fileList: [],
      previewImgList:[],
      isUpdate: false,
      userForm: {
        username:''
      },
      sexs: [{
        value: true,
        label: '男'
      },{
        value: false,
        label: '女'
      }],
      enables: [{
        value: true,
        label: '启用'
      },{
        value: false,
        label: '禁用'
      }],
      accountNonLocks: [{
        value: true,
        label: '锁定'
      },{
        value: false,
        label: '解锁'
      }],
      sex: '',
      enable: '',
      accountNonLock: '',

      roles: [],
      role: '',

      rules: {
        username: [
          { required: true, validator: validateUsername, trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        enable: [
          { required: true, message: '请选择状态', trigger: 'blur' },
        ],
        myPassword: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
        ]
      }
    }
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if(valid){
          this.$emit("submitUserInfo",this.userForm);
        } 
      }) 
    },
    onReset(formName) {
      this.sex = ''
      this.enable = ''
      this.role = ''
      this.$refs[formName].resetFields()
    },
    onReturn() {
      this.$router.go(-1)
    },
    changeSex(value) {
      this.userForm.sex = value 
    },
    changeEnable(value) {
      this.userForm.enabled = value 
    },
    changeAccountNonLock(value) {
      this.userForm.accountNonLocked = value 
    },
    changeRole(value) {
      this.userForm.roles = value
    },
    beforUpload(file) {
      // 校验文件格式
      if(file.type != 'image/png' && file.type !== 'image/jpg' && file.type !== 'image/jpeg') {
        this.$message({
            message: '不支持该格式',
            type: "error"
        });
        return false
      }

      if(Number(file.size / 1024 / 1024) > 5) {
        this.$message({
            message: '文件不允许超过5MB,请重新上传',
            type: "error"
        });
        return false
      }

      return true
    },
    uploadImageMethod(file) {
      let data = new FormData();
      data.append("file",file.file)
      uploadImage(data).then(res => {
        this.$message({
          message: '上传成功',
          type: 'success'
        });
        this.userForm.headImg = res.data.src
        this.initPerviewImg(this.userForm.headImg)
      }).catch(err => {
        this.$message({
          message: err.message,
          type: 'error'
        });
      })
    },
    initPerviewImg(src) {
      this.previewImgList = []
      this.previewImgList.push(src)
    }
  },
  mounted() {
    getAllRole().then(res => {
      this.roles = res.data.records
    }).catch(err => {
      this.$message({
        message: err.message,
        type: 'error'
      });
    })
  },
  watch: {
    userInfo : {
      handler(newValue) {
        this.isUpdate = true
        this.userForm = JSON.parse(JSON.stringify(newValue))
        if(this.userForm.sex === true){
          this.sex = '男'
        } 
        if(this.userForm.sex === false){
          this.sex = '女'
        }

        if(this.userForm.enabled === true){
          this.enable = '启用'
        } 
        if(this.userForm.enabled === false){
          this.enable = '禁用'
        }

        if(this.userForm.accountNonLocked === true){
          this.accountNonLock = '锁定'
        } 
        if(this.userForm.accountNonLocked === false){
          this.accountNonLock = '解锁'
        }

        this.role = this.userForm.roles
        this.operation = 'update'

      }
    }
  }
}
</script>

<style lang="scss" scoped>

.div {
  width: 50vw;
  margin-left: 18%;
}

.selectForm /deep/ .el-form-item__label {
  font-size: 12px;
}

.el-form-item{
  margin-bottom: 0px;
}

.el-input /deep/ .el-input__inner{ 
  height: 32px;
  font-size: 13px;
  box-shadow: none;
  border: 1px solid #e9e9e9;
}

.el-row >>> .el-col {
  margin-top: 5vh;
}

.el-button {
  line-height: 0px;
  height: 32px;
  padding: 12px;
  font-size: 2px;
  border-radius: 20px;
}

.img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-top: 3px;
  border: 3px solid #f2f3f5;
  background: #619fe7;
}

.changeImg {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-left: 8px;
}

.imgPr {
  position: relative;
  display: inline-block;
  text-align: center;
}

.imgPa {
  position: absolute;
  left:0;
  top:0;
  right:0;
  margin-left: 36px;
  cursor: pointer;
  font-size: 22px;
}

.changePassword {
  .el-form-item{
    margin-bottom: 20px;
  }
}

</style>


<style lang="scss" >

/* 自定义宽度 */
#addAndUpdateTable {
  .my-el-select {
    .el-input__inner {
        height: 32px;
    }
  }
}

</style>
